<template>
  <div>
    <div class="common-upload">
      <t-image-viewer v-if="url" :images="[baseUrl + url]" :close-on-esc-keydown="false">
        <template #trigger="{ open }">
          <t-image fit="contain" :src="baseUrl + url" />
          <div class="action">
            <t-icon name="browse" size="1.4em" @click="open" />
            <t-icon name="delete" size="1.4em" @click="onRemove" />
          </div>
        </template>
      </t-image-viewer>
      <t-image v-else class="choose" @click="dialogShow">
        <template #error><t-icon name="add" size="24px" /></template>
      </t-image>
    </div>
    <t-dialog
      v-model:visible="visible"
      :header="t('pages.attachement.choose')"
      width="1000"
      @confirm="dialogConfirm"
      @close="dialogHide"
    >
      <attachement ref="attachementRef" is-diaog />
    </t-dialog>
  </div>
</template>
<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { ref } from 'vue';

import { t } from '@/locales';
import Attachement from '@/pages/content/attachement/index.vue';

const props = defineProps({
  type: {
    type: String,
    default: '',
  },
  url: {
    type: String,
    default: '',
  },
});

const baseUrl = import.meta.env.VITE_API_URL;
const attachementRef = ref();

const emits = defineEmits(['confirm', 'remove']);

const visible = ref(false);
const onRemove = () => {
  emits('remove', props.type, null);
};

const dialogShow = () => {
  visible.value = true;
};
const dialogHide = () => {
  visible.value = false;
};
const dialogConfirm = async () => {
  const checkVal = attachementRef.value.getChecked();
  if (!checkVal) {
    MessagePlugin.info(t('common.chooseOne'));
  }
  dialogHide();
  emits('confirm', props.type, checkVal);
};

defineExpose({
  dialogShow,
  dialogHide,
});
</script>

<style lang="less" scoped>
.common-upload {
  position: relative;
  width: 110px;
  height: 110px;
  .t-image__wrapper {
    width: 100%;
    height: 100%;
  }
  .action {
    opacity: 0;
    position: absolute;
    inset: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 2;
    background-color: rgba(0, 0, 0, 0.6);
    color: var(--td-text-color-anti);
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    transition: 0.2s;
  }
  .choose {
    width: 100%;
    height: 100%;
    cursor: pointer;
  }

  &:hover {
    .action {
      opacity: 1;
    }
  }
}
</style>
